import { computed, ref, unref } from 'vue';

export const useSearch = (props, emit, paginationInfo, resetPage) => {
  const ShSearchRef = ref(null);

  /**
   * @description 是否展示搜索模块
   * @return {Boolean} true | false
   */
  const isShowSearch = computed(() => {
    const { formConfigs, showSearch } = props;
    return showSearch && formConfigs.configs.length > 0;
  });

  /**
   * @description 获取表单数据结构
   * @return {Object} { configs: [], labelWidth: string | number, centerType: true | false }
   */
  const getFormConfig = computed(() => {
    const { configs, labelWidth, centerType } = { ...props.formConfigs };
    return {
      configs,
      labelWidth,
      centerType,
    };
  });

  const search = data => {
    const { current, pageSize } = paginationInfo.value;
    const params = { current, pageSize, ...data.value };
    emit('on-search', params);
  };

  /**
   * @description 搜索
   * @param {Object} 搜索条件
   * @return {Function} onSearch
   */
  const onSearch = data => {
    search(data);
  };

  /**
   * @description 重置搜索
   * @param {Object} 搜索条件置空
   */
  const onReset = data => {
    resetPage();
    search(data);
  };

  /**
   * @description: search设置值的方法
   * @param: {Object} 设置的formModel值
   */
  const setSearchValue = obj => {
    unref(ShSearchRef).setSearchValue(obj);
  };

  /**
   * @description: search组件获取所有值的方法
   * @return {Function} getSearchValue
   */
  const getSearchValue = () => {
    return unref(ShSearchRef).getSearchValue();
  };

  return {
    ShSearchRef,
    isShowSearch,
    getFormConfig,
    onSearch,
    onReset,
    setSearchValue,
    getSearchValue,
  };
};
